<template>
	<view>	
		<u-popup :show="showApprove" @close="onClose" mode="center" custom-style="width:90%;border-radius:24rpx">
		  <view class="auth-box2" @tap.stop.prevent="doNoting">
		    <view class="dialog-title">身份认证</view>
				<view class="dialog-authbox">
					<text style="width: 200rpx;">证件类型：</text>
					<!-- <radio-group @change="changeAuthType">
					  <label class="info-content">
					    <radio style="margin-right: 30rpx" value="01" color="#ff4444"
							:checked="authType == '01'">身份证</radio>
					    <radio value="00" :checked="authType == '00'" color="#ff4444">户口簿</radio>
					  </label>
					</radio-group> -->
          <picker style="width: 100%;" @change="bindPickerChange" :value="certificateTypeIndex" :range="certificateTypeArray">
            <view class="picker-item">
              <view class="uni-input" style="display: inline-block;">{{certificateTypeArray[certificateTypeIndex]}}</view>
              <image class="picker-arrow" src="/static/image/arrow_right.png"></image>
            </view>
          </picker>
				</view>
				<view class="iptbox-new">
					<view class="dialog-iptbox" style="flex: 1;">
					  <view class="dialog-img">
					    <image :src="staticBaseUrl + '/static/image/my/card-1.png'" mode="widthFix"></image>
					  </view>
						<!-- :disabled="memberInfo.approve == '1'" -->
					  <input type="text" class="ipt-username" :value="authParams.certNo" placeholder="请输入证件号码" maxlength="18"
		        @input="bindCardIdChange" />
					</view>
					<view class="btn-confirm idCard-btn" @tap.stop.prevent="idCardSearch">查 询</view>
				</view>
				
				<view class="dialog-iptbox" v-if="authFlag && cardList.length && cardSelectFlag" @tap.stop.prevent="bankCardSelect">
					<view class="dialog-img">
					  <image :src="staticBaseUrl + '/static/image/my/card-3.png'" mode="widthFix"></image>
					</view>
					<input type="text" class="ipt-username" :value="cardHidden(authParams.cardNo)" placeholder="请选择银行卡号" disabled/>
					<image class="select-btn" :src="'/static/image/merchant/' + (showAuthSelect ? 'arrow_down.png' : 'arrow_up.png')"></image>
					<view class="option-view" v-if="showAuthSelect">
						<view v-for="(item, index) in cardList" @tap.stop.prevent="selectBankCard(item)"
						class="bank-item" :key="index">{{cardHidden(item)}}</view>
					</view>
				</view>
				<view class="dialog-iptbox" v-if="authFlag">
				  <view class="dialog-img">
				    <image :src="staticBaseUrl + '/static/image/my/head.png'" mode="widthFix"></image>
				  </view>
				  <input type="number" class="ipt-username" :value="phoneHidden(authParams.phone)" placeholder="手机号码" 
							style="flex: 1"	@input="bindPhoneChange" disabled/>
					<view class="authCode" :style="'color:' + (codeDisabled ? '#FAB7B4' : '#F35C56')" 
					@tap.stop.prevent="getMsgCode">{{messageText}}</view>
				
				</view>
				<view class="dialog-iptbox" v-if="authFlag">
					<view class="dialog-img">
					  <image :src="staticBaseUrl + '/static/image/my/head.png'" mode="widthFix"></image>
					</view>
					<input type="number" class="ipt-username" :value="authParams.authCode" placeholder="验证码" @input="bindAuthCodeChange" />
				</view>
				<view class="errorBox" v-if="showError">
					<view class="error-img">
						<image :src="staticBaseUrl + '/static/image/my/error.png'" mode="widthFix"></image>
					</view>
					<view class="error-info">{{ errInfo }}</view>
				</view>
				<view class="dialog-btnbox" v-if="authFlag">
					<view class="btn-cancel" @tap.stop.prevent="onClose">取消</view>
					<view class="btn-confirm" @tap.stop.prevent="authConfirm2" 
					:style="'color:' + (authDisabled ? '#FAB7B4;opacity: 0.6' : '#fff;opacity: 1')">确定</view>
				</view>
			</view>
		</u-popup>	
	</view>
</template>

<script module="util" lang="wxs" src="../../utils/util.wxs"></script>
<script>
	const app = getApp();
	import util from '../../utils/util';
	import {
		http
	} from '@/utils/commonRequest.js';
	import {
		staticBaseUrl
	} from '@/utils/constant.js';
	export default {
		name:"toAuth",
		data() {
			return {
        certificateTypeIndex:1,
        certificateTypeArray:['户口簿','身份证','护照','临时身份证','港澳通行证','台湾通行证'],
				staticBaseUrl,
				show: false,
				/** 去认证上传参数 */
				authParams: {
				  custName: '',
				  certTp: '1',
				  certNo: '',
				  cardNo: '',
					phone: '',
				},
				userInfo: {},
				memberInfo: null,
				phone: '',
				toAuthLoading: false,   // 认证提交loading
				authType: '01',
				showError: false,
				approve: null,
				showApprove: false,
				authFlag: null,
				showAuthSelect: false,
				cardList: null,
				messageText: '获取验证码',
				codeDisabled: false,
				authDisabled: true,
				errInfo: '',
        cardSelectFlag: true,
			};
		},
		props: {
			
			isEdit: {
				type: Boolean,
				default: false
			}
		},
		
		created(){
			// #ifdef H5
			this.memberInfo = uni.getStorageSync('memberInfo')
			// #endif
			// #ifdef MP-WEIXIN
			this.memberInfo = app.globalData.memberInfo
			// #endif
			
		},
		
		methods: {
			// 关闭弹框
			onClose: function() {
				this.showApprove = false;
				this.errInfo = '';
				this.authDisabled = true;
				this.showError = false;
				this.authParams = {
				  custName: '',
				  certTp: '1',
				  cardNo: '',
					phone: '',
					certNo: ''
				}
			},
			
			openShow: function(phone) {
				const that = this;
				this.phone = phone
				uni.showModal({
					title: '温馨提示',
					content: '您未注册认证积分商城，请先完成认证后进行下单',
					confirmColor: '#ff4444',
					showCancel: false,
					complete(res) {
						that.showApprove = true;
					}
				});
			},
			
			// openShow: function(phone) {
			// 	console.log('111',phone)
			// 	// this.$refs.toAuth.openShow()
			// 	this.showApprove = true;
			// 	this.phone = phone
			// },
			
			// 银行卡号脱敏
			cardHidden(no) {
				// return no.replace(/(?<=\d{4})\d+(?=\d{4})/," **** **** ")
				return no.replace(/^(.{4})(?:\d+)(.{4})$/, "$1 **** **** $2")
			},
			
			phoneHidden(phone) { //手机号脱敏
			  if (null == phone || undefined == phone || 'undefined' == phone || 0 == phone.length) {
			    return '';
			  }
			  phone = phone + '';
			  return phone.substring(0, 3) + '****' + phone.substring(7);
			},
			
			// 认证类型
			// changeAuthType: function(e){
			// 	let value = e.detail.value;
			// 	this.authType = value;
			// 	this.authParams.authCode = '';
			// 	this.authParams.phone = '';
			// 	this.authParams.cardNo = '';
			// 	this.authDisabled = true;
			// 	this.cardList = [];
			// 	this.authFlag = false;
			// },
      bindPickerChange: function(e) {
        let certificateMap = [
          {index: "00", value: "户口簿"},
          {index: "01", value: "身份证"},
          {index: "02", value: "护照"},
          {index: "03", value: "军官证"},
          {index: "04", value: "士兵证"},
          {index: "05", value: "港澳通行证"},
          {index: "06", value: "台湾通行证"},
          {index: "07", value: "临时身份证"},
          {index: "08", value: "外国人居留证"},
          {index: "09", value: "警官证"},
          {index: "10", value: "无身份证"},
          {index: "11", value: "其他证件"},
          {index: "12", value: "组织机构代码"},
          {index: "13", value: "营业执照号"},
          {index: "14", value: "批文"},
          {index: "15", value: "主管证明"},
          {index: "16", value: "组织代码证"},
          {index: "17", value: "电子现金证件"},
          {index: "18", value: "港澳居住证"},
          {index: "19", value: "台湾居住证"}
        ]
        console.log('picker发送选择改变，携带值为', e.detail.value)
        // this.index = e.detail.value
        this.certificateTypeIndex = e.detail.value
        let value = e.detail.value;
        let a = certificateMap.find(item => {
          return item.value == this.certificateTypeArray[value];
        })
				this.authType = a.index;
        console.log("authType", this.authType);
				this.authParams.authCode = '';
				this.authParams.phone = '';
				this.authParams.cardNo = '';
				this.authDisabled = true;
				this.cardList = [];
				this.authFlag = false;
      },
			
			doNoting() {
			  console.log('占位：函数 doNoting 未声明');
			},
			
			bindAuthCodeChange:function(e) {
				this.authParams.authCode = e.detail.value;
				this.authDisabled = !(this.authParams.phone && this.authParams.authCode)
			},
			
			bindPhoneChange: function(e){
				this.authParams.phone = e.detail.value;
				this.authDisabled = !(this.authParams.phone && this.authParams.authCode)
			},
			
			/** 弹窗输入框信息获取 */
			bindNameChange: function(e) {
			  this.authParams.custName = e.detail.value;
			},
			
			bindCardIdChange: function(e) {
			  this.authParams.certNo = e.detail.value; 
				this.authParams.authCode = '';
				this.authParams.phone = '';
				this.authParams.cardNo = '';
				this.authDisabled = true;
				this.cardList = [];
				this.authFlag = false;
			},
			
			bindCardChange: function(e) {
			  this.authParams.cardNo = e.detail.value;
			},
			
			// 认证new
			authConfirm2: function() {
				let that = this;
				let cardIdReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; //身份证号正则
				let url = 'mtBankInfo/userAuthByIdno';
				if(this.toAuthLoading) { return }
				if(this.memberInfo.approve == '1'){ url = 'mtBankInfo/updateAuthByIdno' }
				
				if(!(this.authParams.phone && this.authParams.authCode)){
					return
				}
        if(that.authType == '00'|| that.authType == '01'){
          if (!cardIdReg.test(this.authParams.certNo)) {
            uni.showToast({
              icon: 'none',
              title: that.authType == '01' ? '身份证号格式错误，请重新输入' : '户口簿格式错误，请重新输入'
            });
            return;
          }
        }
				if(util.isEmpty(this.authParams.authCode)){
					uni.showToast({
					  icon: 'none',
					  title: '请输入正确短信验证码'
					});
					return;
				}
        console.log("this.authParams",this.authParams);
				let params = {
					memberId: this.memberInfo.id,
					idno: this.authParams.certNo,
					phone: this.authParams.phone,
					code: this.authParams.authCode,
					authFlag: this.authType,
					bankType: uni.getStorageSync('bankType'),
          cardNo: this.authParams.cardEnc
				}
				// if(this.authParams.cardNo){
				// 	params.cardNo = this.authParams.cardEnc
				// }
				uni.showLoading({
					title: '提交中'
				})
				this.toAuthLoading = true
				http.get(url, {params: params})
				  .then((res) => {
						res = res.data;
						if(res.code == '200'){
							if(res.authFlag){
								uni.setStorageSync('authFlag',res.authFlag)
							}
							uni.showToast({
							  title: that.memberInfo.approve == '1' ? '修改成功' : '认证成功',
							  icon: 'success'
							});
							that.onClose()
							that.getDetailMemberInfo()
						}else {
							that.showError = true
							that.errInfo = res.msg
			      }
						uni.hideLoading()
						that.toAuthLoading = false
					}).catch((err) => {
						uni.hideLoading()
						that.toAuthLoading = false
			      console.log(err);
			    });
			},
				
			// 获取短信验证码
			getMsgCode: function(){
				if(this.codeDisabled){
					return;
				}
				
				let that = this;
				let phone = that.authParams.phone;
				if (util.isEmpty(phone) || !util.verifyPhone(phone)) {
					util.tips('请输入正确的手机号！');
					return;
				}
				
				this.codeDisabled = true;
				
				let params = { phone: phone }
				uni.showLoading({
					title: '发送中'
				});
				http.get('/mtBankInfo/sendCodeMt', {params: params})
					.then((res) => {
						res = res.data;
						uni.hideLoading();
						if ('200' == res.code) {
							util.message('验证码已发送');
							let second = 60;
							let a = setInterval(function() {
								second--;
								if (second == 0) {
									that.messageText = '获取验证码'
									that.codeDisabled = false
									clearInterval(a);
								} else {
									that.messageText = second + 'S后获取'
								}
							}, 1000);
						}else {
							util.message(res.msg);
							that.codeDisabled = false
						}
					}).catch((err) => {
						uni.hideLoading();
						that.codeDisabled = false
						util.message('获取验证码失败')
						console.log('验证码err',err)
				})
			},	
			
			// 身份证查询
			idCardSearch: function(){
				let that = this;
				let cardIdReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; //身份证号正则
				let url = '/mtBankInfo/getPhoneByIdno';
				if(this.memberInfo.approve == '1'){
					url = '/mtBankInfo/getPhoneByIdnoUpdate'
				}
				if(that.authType == '00'|| that.authType == '01'){
          if (!cardIdReg.test(this.authParams.certNo)) {
            uni.showToast({
              icon: 'none',
              title: that.authType == '01' ? '身份证号格式错误，请重新输入' : '户口簿格式错误，请重新输入'
            });
            return;
          }
        }
				let params = {
					idno: this.authParams.certNo,
					memberId: this.memberInfo.id,
					authFlag: this.authType
				}
				that.showError = false;
				uni.showLoading({
					title: '查询中'
				});
				http.get(url, {params: params})
					.then((res) => {
						uni.hideLoading()
						res = res.data;
						if(res.code == '200'){
							console.log('身份证查询',res);
							if(res.bankType){
								uni.setStorageSync('bankType',res.bankType)
							}
              // 情况1：总行
              if(res.phone && res.phoneEnc){
                console.log("总行");
                that.cardSelectFlag = false;
                that.authParams.phone = res.phone;
                that.authParams.phoneEnc = res.phoneEnc;
                that.authParams.cardEnc = res.cardEnc;
                console.log("that.authParams", that.authParams);
                that.authFlag = true
                if(res.phone == ''){
                  uni.showToast({
                    icon: 'none',
                    title: '未查询到您在我行的预留手机号，请至柜面录入后进行认证'
                  });
                }
              }
              // 情况2：村行
              else if(res.cardList){
                console.log("村行");
                that.cardSelectFlag = true;
                if(res.cardList && res.cardList.length > 0){
                  that.cardList = res.cardList
                  that.authParams.cardNo = res.cardList[0]
                  that.selectBankCard(res.cardList[0])
                  that.authFlag = true
                }else{
                  uni.showToast({
                    icon: 'none',
                    title: '很抱歉，未查询到您的银行卡信息，暂不支持注册'
                  });
                  that.authFlag = false;
                  that.cardList = null;
                  that.authParams.cardNo = null;
                  that.authParams.phone = ''
                }
              }
						}else{
							uni.showToast({
								icon: 'none',
								title: res.msg
							});
						}
						that.authParams.authCode = ''
						that.authDisabled = true
					}).catch((err) => {
						uni.hideLoading()
			      console.log(err);
			    })
				
			},
			
			// 选择银行卡号
			selectBankCard: function(item){
				this.authParams.cardNo = item;
				let that = this;
				http.get('/mtBankInfo/getPhoneByCard', {
					params: { 
						cardNo: that.authParams.cardNo,
						authFlag: that.authType,
						bankType: uni.getStorageSync('bankType')
					}
				})
					.then((res) => {
						res = res.data;
						if(res.code == '200'){
							console.log('选择银行卡号获取手机号===',res)
							that.authParams.phone = res.phone;
						}else{
							uni.showToast({
								icon: 'none',
								title: res.msg
							});
						}
					})
				if(this.showAuthSelect){ this.bankCardSelect() }
			},
			
			// 银行卡号选择框
			bankCardSelect: function(){
				this.showAuthSelect = !this.showAuthSelect
			},
			
			/** 获取详细的会员信息 */
			getDetailMemberInfo: function() {
				console.log('??????????????????')
			  var that = this;
			  http.get('/personal/userInfo', {})
			    .then((res) => {
			      if ('200' == res.data.code) {
			        console.log('userInfo',res.data);
			        let userinfo = res.data.userinfo;
							that.authParams.certNo = userinfo.idno;
							console.log('ppp',that.authParams)
			        this.userInfo = userinfo
							uni.setStorageSync('noApproveFlag',userinfo.approve != '1')
							uni.setStorageSync('authFlag',userinfo.idType)
			      }
			    })
			    .catch((err) => {
			      console.log(err);
			    });
			},
		}
	}
</script>

<style>
	.phone-view{
		padding: 50rpx 34rpx;
		box-sizing: border-box;
	}
	
	.authCode{
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		word-break: keep-all;
		padding-right: 10rpx;
	}
	
	.auth-box2 {
	  padding: 50rpx 34rpx;
	  box-sizing: border-box;
	}
	
	.idCard-btn{
		width: auto !important;
		min-width: 160rpx;
		padding: 0 10rpx;
		margin-left: 10rpx;
	}
	
	.select-btn {
	  width: 24rpx;
	  height: 24rpx;
	}
	
	.option-view{
		position: absolute;
		left: 0;
		top: 94rpx;
		width: 100%;
		max-height: 200rpx;
		background-color: #fff;
		border: 2rpx solid #eee;
		border-radius: 24rpx;
		overflow-y: scroll;
		padding: 20rpx 0 20rpx 54rpx;
		z-index: 9;
	}
	
	.bank-item{
		font-size: 28rpx;
		padding: 12rpx 0;
	}

  .dialog-title {
    text-align: center;
    color: #000;
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .dialog-iptbox {
    display: flex;
    position: relative;
    padding-left: 16rpx;
    font-size: 28rpx;
    height: 96rpx;
    background-color: #eee;
    border-radius: 24rpx;
    align-items: center;
    margin-bottom: 16rpx;
  }
	
	.dialog-authbox{
		display: flex;
		align-items: center;
		padding-left: 16rpx;
		font-size: 28rpx;
		height: 96rpx;
	}
	
	.iptbox-new{
		display: flex;
		align-items: center;
	}

  .dialog-img {
    width: 48rpx;
    height: 48rpx;
    margin-right: 24rpx;
  }

  .dialog-img image {
    width: 100%;
  }
	
	.ipt-username{
	  width: 80%
	}
	
	.errorBox {
	  margin-top: 40rpx;
	  display: flex;
	}
	
	.error-img {
	  width: 32rpx;
	  height: 32rpx;
	  margin-right: 14rpx;
	}
	
	.error-img image {
	  width: 100%;
	}
	
	.error-info {
	  color: #666;
	  font-size: 26rpx;
	  font-weight: bold;
	}
	
	.dialog-btnbox {
	  padding: 40rpx 0rpx;
	  display: flex;
	  justify-content: space-between;
	}
	
	.btn-cancel,
	.btn-confirm {
	  width: 260rpx;
	  height: 84rpx;
	  background-color: #fff;
	  color: #666;
	  font-size: 34rpx;
	  line-height: 84rpx;
	  border: 1rpx solid #eaeaea;
	  border-radius: 42rpx;
	  text-align: center;
	}
	
	.btn-confirm {
	  background: linear-gradient(140deg, #ffc996 0%, #ed176e 100%);
	  color: white;
	}
	
	.u-safe-bottom {
	  display: none !important;
	}

  .picker-item{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .picker-arrow {
    width: 24rpx;
    height: 24rpx;
    transform: rotate(90deg);
  }
</style>